<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['laiqianle:terminal:edit']" :disabled="single" icon="Edit" plain type="success" @click="handleUpdate">修改 </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button v-hasPermi="['laiqianle:terminal:export']" icon="Download" plain type="warning" @click="handleExport">导出 </el-button>
      </el-col>

      <el-col :span="1.5">
        <!--        <el-button icon="upload" plain type="primary" @click="handleReport">上报机构</el-button>-->
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="terminalList" @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="55" />
      <el-table-column align="center" label="外部商户号" prop="outMerchantNo" width="180" />
      <el-table-column align="center" label="外部终端号" prop="outTerminalNo" width="150" />
      <el-table-column align="center" label="签购单名称" prop="terminalName" width="200" />
      <el-table-column align="center" label="码牌展示名称" prop="merchantCodeName" width="200" />
      <el-table-column align="center" label="设备号" prop="deviceSn" width="100" />
      <el-table-column align="center" label="联系电话" prop="contactTel" width="130" />
      <el-table-column align="center" label="安装地址" prop="installAddress" width="150" />
      <el-table-column align="center" label="省份" prop="installProvince" width="120" />
      <el-table-column align="center" label="城市" prop="installCity" width="120" />
      <el-table-column align="center" label="地区" prop="installDistrict" width="120" />
      <el-table-column align="center" label="查询" prop="isOpenConsume">
        <template #default="scope">
          <dict-tag :options="sys_my_yes_no" :value="scope.row.isOpenConsume" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="退货" prop="isOpenRefund">
        <template #default="scope">
          <dict-tag :options="sys_my_yes_no" :value="scope.row.isOpenRefund" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="消费类" prop="isOpenQueryTrade">
        <template #default="scope">
          <dict-tag :options="sys_my_yes_no" :value="scope.row.isOpenQueryTrade" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="预授权类" prop="isOpenPreauthorize">
        <template #default="scope">
          <dict-tag :options="sys_my_yes_no" :value="scope.row.isOpenPreauthorize" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="借记卡" prop="isOpenDebitCard">
        <template #default="scope">
          <dict-tag :options="sys_my_yes_no" :value="scope.row.isOpenDebitCard" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="贷记卡" prop="isOpenCreditCard">
        <template #default="scope">
          <dict-tag :options="sys_my_yes_no" :value="scope.row.isOpenCreditCard" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="准贷记卡" prop="isOpenSemiCreditCard">
        <template #default="scope">
          <dict-tag :options="sys_my_yes_no" :value="scope.row.isOpenSemiCreditCard" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="预付费卡" prop="isOpenPrepaidCard">
        <template #default="scope">
          <dict-tag :options="sys_my_yes_no" :value="scope.row.isOpenPrepaidCard" />
        </template>
      </el-table-column>

      <el-table-column align="center" label="二维码预授权类" prop="isOpenPrepaidCard">
        <template #default="scope">
          <dict-tag :options="sys_my_yes_no" :value="scope.row.isOpenPreauthorizeQr" />
        </template>
      </el-table-column>

      <el-table-column :fixed="'right'" align="center" class-name="small-padding fixed-width" label="操作" width="240">
        <template #default="scope">
          <el-button v-hasPermi="['laiqianle:terminal:edit']" icon="Edit" type="text" @click="handleUpdate(scope.row)"> 修改 </el-button>

          <!--          <el-button icon="upload" type="text" @click="handleReport">上报机构</el-button>-->

          <el-button icon="upload" type="text" @click="shwoQrcodeHandle(scope.row)">查看马牌</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum" :total="total" @pagination="getList" />

    <!-- 添加或修改商户终端对话框 -->
    <el-drawer v-model="open" :title="title" append-to-body size="45%">
      <el-alert title="码牌展示名称最多输入13个字符" :closable="false" type="success" />

      <el-divider />

      <el-form ref="terminalRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="码牌展示名称" prop="merchantCodeName">
          <el-input v-model="form.merchantCodeName" maxlength="13" show-word-limit placeholder="码牌展示名称" />
        </el-form-item>

        <el-form-item label="签购单名称" prop="terminalName">
          <el-input v-model="form.terminalName" placeholder="请输入签购单名称" />
        </el-form-item>
        <el-form-item label="设备号" prop="deviceSn">
          <el-input v-model="form.deviceSn" placeholder="请输入设备号" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactTel">
          <el-input v-model="form.contactTel" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="安装地址" prop="installAddress">
          <el-input v-model="form.installAddress" placeholder="请输入安装地址" />
        </el-form-item>
        <el-form-item label="省市区" required>
          <el-row :gutter="10">
            <el-col :span="8">
              <el-form-item prop="installProvince">
                <el-select v-model="form.installProvince" :clearable="true" placeholder="请选择省" @change="handleProvinceChange">
                  <el-option v-for="item1 in provinceOptions" :key="item1.id" :label="item1.name" :value="item1.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="installCity">
                <el-select v-model="form.installCity" :clearable="true" placeholder="请选择市" @change="handleCityChange">
                  <el-option v-for="item1 in cityOptions" :key="item1.id" :label="item1.name" :value="item1.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="installDistrict">
                <el-select v-model="form.installDistrict" :clearable="true" placeholder="请选择区">
                  <el-option v-for="item1 in districtOptions" :key="item1.id" :label="item1.name" :value="item1.id" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
        <el-row>
          <el-form-item label="交易权限-查询" label-width="150px" prop="isOpenConsume">
            <el-switch v-model="form.isOpenConsume" />
          </el-form-item>
          <el-form-item label="交易权限-退货" label-width="150px" prop="isOpenRefund">
            <el-switch v-model="form.isOpenRefund" />
          </el-form-item>
          <el-form-item label="交易权限-消费类" label-width="150px" prop="isOpenQueryTrade">
            <el-switch v-model="form.isOpenQueryTrade" />
          </el-form-item>
          <el-form-item label="交易权限-预授权类" label-width="150px" prop="isOpenPreauthorize">
            <el-switch v-model="form.isOpenPreauthorize" />
          </el-form-item>
          <el-form-item label="卡类型权限-借记卡" label-width="150px" prop="isOpenDebitCard">
            <el-switch v-model="form.isOpenDebitCard" />
          </el-form-item>
          <el-form-item label="卡类型权限-贷记卡" label-width="150px" prop="isOpenCreditCard">
            <el-switch v-model="form.isOpenCreditCard" />
          </el-form-item>
          <el-form-item label="卡类型权限-准贷记卡" label-width="150px" prop="isOpenSemiCreditCard">
            <el-switch v-model="form.isOpenSemiCreditCard" />
          </el-form-item>
          <el-form-item label="卡类型权限-预付费卡" label-width="150px" prop="isOpenPrepaidCard">
            <el-switch v-model="form.isOpenPrepaidCard" />
          </el-form-item>
          <el-form-item label="交易权限-二维码预授权类" label-width="190px" prop="isOpenPreauthorizeQr">
            <el-switch v-model="form.isOpenPreauthorizeQr" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-alert :closable="false" class="mb20" show-icon title="温馨提示：同地址请上传增机单,否则请上传门店照片(最多支持5张)" type="info" />
          <el-col v-for="(item1, index1) in form.fileList" :key="item1" :span="8">
            <el-form-item :label="`上传图片`" :prop="`imgList[${index1}].path`" label-width="80px">
              <ImageUpload1 v-model="item1.path" />
              <div class="img-wrap">
                <el-button v-if="index1 + 1 === form.fileList.length && form.fileList.length < 5" type="primary" @click="form.fileList.push({ path: null })">
                  添加
                </el-button>
                <el-button v-if="form.fileList.length > 1" type="danger" @click="form.fileList.splice(index1, 1)">删除 </el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 展示马牌 -->
    <el-dialog v-model="showQrcodeOpen" append-to-body width="600px">
      <ImagePreview v-if="showQrcode" :src="QrcodeUrl" />
      <!--      <template #footer>-->
      <!--        <div class="dialog-footer">-->
      <!--          <el-button type="primary" @click="submitForm">下载</el-button>-->
      <!--        </div>-->
      <!--      </template>-->
    </el-dialog>
  </div>
</template>

<script lang="ts" name="Terminal" setup>
  import { addTerminal, getTerminal, listTerminal, showQrcode, updateTerminal } from '@/api/laiqianle/terminal';
  import { getCurrentInstance, reactive, ref, toRefs } from 'vue';
  import { areaListByParentId, reportOrg } from '@/api/laiqianle/register';
  import ImageUpload1 from '@/views/laiqianle/register/ImageUpload.vue';

  const props = defineProps({
    detailId: {
      type: String,
      default: '',
    },
  });
  const { proxy } = getCurrentInstance();
  const { sys_my_yes_no } = proxy.useDict('sys_my_yes_no');

  const terminalList = ref([]);
  const open = ref(false);
  const showQrcodeOpen = ref(false);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);
  const title = ref('');
  const QrcodeUrl = ref('');

  // 省市区
  interface provinces {
    id: number;
    name: string;
    code: string;
    pcode: string;

    [key: string]: any;
  }

  let provinceOptions = ref<provinces[]>([]);
  let cityOptions = ref<provinces[]>([]);
  let districtOptions = ref<provinces[]>([]);
  const getProvinceList = async (parentId) => {
    if (parentId === '') return [];
    const { data } = await areaListByParentId(parentId);
    return data;
  };
  provinceOptions.value = await getProvinceList(0);

  const handleProvinceChange = async (value) => {
    cityOptions.value = await getProvinceList(value);
    form.value['installCity'] = null;
    form.value['installDistrict'] = null;
  };

  const handleCityChange = async (value) => {
    districtOptions.value = await getProvinceList(value);
    form.value['installDistrict'] = null;
  };

  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      outMerchantNo: props.detailId,
      outTerminalNo: null,
      terminalName: null,
      deviceSn: null,
      contactTel: null,
      installAddress: null,
      installProvince: null,
      installCity: null,
      installDistrict: null,
      isOpenConsume: null,
      isOpenRefund: null,
      isOpenQueryTrade: null,
      isOpenPreauthorize: null,
      isOpenDebitCard: null,
      isOpenCreditCard: null,
      isOpenSemiCreditCard: null,
      isOpenPrepaidCard: null,
    },
    rules: {
      outMerchantNo: [{ required: true, message: '外部商户号不能为空', trigger: 'blur' }],
      outTerminalNo: [{ required: true, message: '外部终端号不能为空', trigger: 'blur' }],
      terminalName: [{ required: true, message: '签购单名称不能为空', trigger: 'blur' }],
      contactTel: [{ required: true, message: '联系电话不能为空', trigger: 'blur' }],
      installAddress: [{ required: true, message: '安装地址不能为空', trigger: 'blur' }],
      installProvince: [{ required: true, message: '省份不能为空', trigger: 'blur' }],
      installCity: [{ required: true, message: '城市不能为空', trigger: 'blur' }],
      installDistrict: [{ required: true, message: '区县不能为空', trigger: 'blur' }],
    },
  });

  const { queryParams, form, rules } = toRefs(data);

  /** 查询来钱乐终端列表 */
  function getList() {
    loading.value = true;
    listTerminal(queryParams.value).then((response) => {
      terminalList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    });
  }

  // 取消按钮
  function cancel() {
    open.value = false;
    reset();
  }

  // 表单重置
  function reset() {
    form.value = {
      id: null,
      outMerchantNo: props.detailId,
      outTerminalNo: null,
      terminalName: null,
      merchantCodeName: null,
      deviceSn: null,
      contactTel: null,
      installAddress: null,
      installProvince: null,
      installCity: null,
      installDistrict: null,
      isOpenConsume: null,
      isOpenRefund: null,
      isOpenQueryTrade: null,
      isOpenPreauthorize: null,
      isOpenDebitCard: null,
      isOpenCreditCard: null,
      isOpenSemiCreditCard: null,
      isOpenPrepaidCard: null,
      isOpenPreauthorizeQr: null,
      createBy: null,
      createTime: null,
      updateBy: null,
      updateTime: null,
      delFlag: null,
      fileList: [{ path: null }],
    };
    proxy.resetForm('terminalRef');
  }

  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
  }

  /** 重置按钮操作 */
  function resetQuery() {
    proxy.resetForm('queryRef');
    handleQuery();
  }

  // 多选框选中数据
  function handleSelectionChange(selection) {
    ids.value = selection.map((item) => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
  }

  /** 新增按钮操作 */
  function handleAdd() {
    reset();
    open.value = true;
    title.value = '添加商户终端';
  }

  /** 修改按钮操作 */
  function handleUpdate(row) {
    reset();
    const _id = row.id || ids.value;
    getTerminal(_id).then(async (response) => {
      form.value = {
        ...response.data,
        isOpenConsume: response.data.isOpenConsume === 'true',
        isOpenRefund: response.data.isOpenRefund === 'true',
        isOpenQueryTrade: response.data.isOpenQueryTrade === 'true',
        isOpenPreauthorize: response.data.isOpenPreauthorize === 'true',
        isOpenDebitCard: response.data.isOpenDebitCard === 'true',
        isOpenCreditCard: response.data.isOpenCreditCard === 'true',
        isOpenSemiCreditCard: response.data.isOpenSemiCreditCard === 'true',
        isOpenPrepaidCard: response.data.isOpenPrepaidCard === 'true',
        isOpenPreauthorizeQr: response.data.isOpenPreauthorizeQr === 'true',
        fileList: response.data.fileList && response.data.fileList.length > 0 ? response.data.fileList : [{ path: null }],
      };

      cityOptions.value = await getProvinceList(response.data.installProvince);
      districtOptions.value = await getProvinceList(response.data.installCity);
      open.value = true;
      title.value = '修改商户终端';
    });
  }

  /** 提交按钮 */
  function submitForm() {
    proxy.$refs['terminalRef'].validate((valid) => {
      if (valid) {
        form.value['fileList'] = form.value['fileList']
          .filter((item) => item.path !== null)
          .map((item, index) => ({
            ...item,
            fileTypeId: index + 101,
          }));

        if (form.value['id'] != null) {
          updateTerminal(form.value).then(() => {
            proxy.$modal.msgSuccess('修改成功');
            open.value = false;
            getList();
          });
        } else {
          addTerminal(form.value).then(() => {
            proxy.$modal.msgSuccess('新增成功');
            open.value = false;
            getList();
          });
        }
      }
    });
  }

  /** 导出按钮操作 */
  function handleExport() {
    proxy.download(
      'tenant/device/export',
      {
        ...queryParams.value,
      },
      `terminal_${new Date().getTime()}.xlsx`,
    );
  }

  /** 上报机构 */
  const handleReport = (row) => {
    const _ids = row.id || ids.value;
    proxy.$modal
      .confirm('是否确认上报商户商户注册编号为"' + _ids + '"的数据项？')
      .then(function () {
        return reportOrg(_ids);
      })
      .then(() => {
        getList();
        proxy.$modal.msgSuccess('上报成功');
      })
      .catch(() => {});
  };

  /**
   * 查看马牌
   * @param row
   */
  function shwoQrcodeHandle(row) {
    showQrcode(row).then((res) => {
      showQrcodeOpen.value = true;
      QrcodeUrl.value = res.data;
    });
  }

  getList();
</script>
<style lang="scss" scoped>
  .mb20 {
    margin-bottom: 20px !important;
  }

  .img-wrap {
    width: 100%;
    box-sizing: border-box;
    padding-right: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 10px;
  }
</style>
